package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.constant.MessageConstant;
import com.atguigu.constant.RedisConstant;
import com.atguigu.entity.PageResult;
import com.atguigu.entity.QueryPageBean;
import com.atguigu.entity.Result;
import com.atguigu.pojo.Setmeal;
import com.atguigu.service.SetmealService;
import com.atguigu.util.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Reference
    SetmealService setmealService;
    @Autowired
    JedisPool jedisPool;

    @RequestMapping("/upload.do")
    public Result upload(@RequestParam("imgFile") MultipartFile multipartFile) throws IOException {
      //  String name = multipartFile.getName();//文件上传的标签名字
         String filename = multipartFile.getOriginalFilename();//文件的名字
         String substring = filename.substring(filename.lastIndexOf("."));//获取后缀名
         filename =  UUID.randomUUID()+"_"+System.currentTimeMillis()+substring;

        byte[] bytes = multipartFile.getBytes();
        QiniuUtils.upload2Qiniu(bytes,filename);
        //把图片的名字保存到redis
        Jedis jedis = jedisPool.getResource();
        jedis.sadd(RedisConstant.SETMEAL_PIC_RESOURCES,filename);

        return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,filename);
    }

    //添加
    @RequestMapping("/add.do")
    public Result add(@RequestBody Setmeal setmeal, Integer[] travelgroupIds){
        try {
            setmealService.add(setmeal,travelgroupIds);
            return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }
    }

    //分页
    @RequestMapping("/findPage.do")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return setmealService.findPage(queryPageBean);
    }
}
